package com.ksyzt.ksite2.client.column;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.ksyzt.gwt.client.common.GwtUtil;
import com.ksyzt.gwt.client.common.MessageComposite;
import com.ksyzt.gwt.client.common.PostImageProxy;
import com.ksyzt.gwt.client.common.SysResource;
import com.ksyzt.gwt.client.event.MessageEvent;
import com.ksyzt.gwt.client.event.MessageHandler;
import com.ksyzt.gwt.client.ui.richeditor.SimpleClickEditor;
import com.ksyzt.ksite2.client.common.ServerProxy;
import com.ksyzt.ksite2.shared.OrgType;
import com.ksyzt.ksite2.shared.SysConst;
import com.ksyzt.ksite2.shared.modle.COLUMNObj;

public class ColumnEditor extends MessageComposite implements RequiresResize {

	private static ColumnEditorUiBinder uiBinder = GWT
			.create(ColumnEditorUiBinder.class);

	interface ColumnEditorUiBinder extends UiBinder<Widget, ColumnEditor> {
	}

	private ChangeHandler m_type_change = new ChangeHandler() {

		@Override
		public void onChange(ChangeEvent event) {
			setImage(listType.getSelectedIndex());
		}
	};

	public ColumnEditor() {

		initWidget(uiBinder.createAndBindUi(this));
		btnSave.setEnabled(false);
		btnCreateChild.setEnabled(false);
		listType.addItem("分类节点", ColumnType.CT_CATALOG + "");
		listType.addItem("内容列表", ColumnType.CT_LIST + "");
		listType.addItem("图片集合", ColumnType.CT_PICTURE + "");
		listType.addItem("视频集合", ColumnType.CT_VIDEO + "");
		listType.addItem("单篇文章", ColumnType.CT_ARTICLE + "");
		listType.setSelectedIndex(0);
		listType.addChangeHandler(m_type_change);
		txtTag.addFocusHandler(m_tags_edit_focus_handler);

	}

	@UiField
	Button btnClearCache;
	@UiField
	TextBox txtName;
	@UiField
	TextBox txtRank;
	@UiField
	SimpleClickEditor txtDesc;
	@UiField
	TextBox txtURL;
	@UiField
	TextBox txtTag;
	@UiField
	TextBox txtCode;
	@UiField
	Label lbID;
	@UiField
	Button btnSave;
	@UiField
	Button btnCreateChild;
	@UiField
	CheckBox checkDisply;
	@UiField
	TextBox txtBBSID;
	@UiField
	TextBox txtCSS;

	@UiField
	Image imgType;
	@UiField
	Label lbPATH;

	int m_orgtype;
	int m_whoid;
	COLUMNObj m_column;
	COLUMNObj m_parent;

	public void edit(int userid, int orgtype, COLUMNObj parent, COLUMNObj column) {
		movefalsh();
		message("");

		m_column = column;
		m_orgtype = orgtype;
		m_whoid = userid;

		m_parent = parent;

		if (m_column != null) {
			txtName.setValue(m_column.getNAME());
			txtRank.setValue(m_column.getRANKVAL().toString());
			txtURL.setValue(m_column.getURL());
			txtDesc.setValue(m_column.getDESCRIPTION());
			txtCode.setValue(m_column.getCODE());
			txtTag.setValue(m_column.getTAG());
			checkDisply.setValue(m_column.getDISPLAY() > 0 ? true : false);
			btnCreateChild.setEnabled(true);
			btnSave.setEnabled(true);
			lbID.setText("编辑" + OrgType.getOrgNameByType(m_orgtype) + ":"
					+ m_column.getID());
			txtBBSID.setValue(m_column.getUSERVALUE());
			txtCSS.setValue(m_column.getCSS());
			lbPATH.setText(m_column.getTEXTPATH());
			btnClearCache.setEnabled(true);
			m_proxy.showPicture(strImagepath, m_column.getID());

			setImage(m_column.getCOLUMNTYPE());
			listType.setSelectedIndex(m_column.getCOLUMNTYPE());

			sureCanDelete();
		} else {

			clearData();
		}

	}

	private void setImage(Integer columntype) {
		String icon = "";
		switch (columntype) {

		case ColumnType.CT_CATALOG:
			icon = SysResource.INSTANCE.col_catalog().getSafeUri().asString();
			break;
		case ColumnType.CT_LIST:
			icon = SysResource.INSTANCE.col_list().getSafeUri().asString();
			break;
		case ColumnType.CT_PICTURE:
			icon = SysResource.INSTANCE.col_picture().getSafeUri().asString();
			break;
		case ColumnType.CT_VIDEO:
			icon = SysResource.INSTANCE.col_video().getSafeUri().asString();
			break;
		case ColumnType.CT_ARTICLE:
			icon = SysResource.INSTANCE.col_article().getSafeUri().asString();
			break;	
		}

		imgType.setUrl(icon);

	}

	TagsEditor m_tag_editor;
	PopupPanel m_p = new PopupPanel();
	protected MessageHandler m_tag_message_handler = new MessageHandler() {

		@Override
		public void onMessage(Object sender, Integer message, Object value) {
			if (message == MessageEvent.OK) {
				String tag = (String) value;
				txtTag.setValue(tag);
			}

			m_p.hide();

		}
	};
	private FocusHandler m_tags_edit_focus_handler = new FocusHandler() {

		@Override
		public void onFocus(FocusEvent arg0) {

			if (m_tag_editor == null) {
				m_tag_editor = new TagsEditor();
				m_p.add(m_tag_editor);
				m_tag_editor.addMessageHandler(m_tag_message_handler);
			}
			// int
			// left=txtTAGS.getAbsoluteLeft()+txtTAGS.getOffsetWidth()-m_tag_editor.getOffsetWidth();
			// int top=txtTAGS.getOffsetHeight()+txtTAGS.getAbsoluteTop();
			m_p.showRelativeTo(txtTag);

			m_tag_editor.initTags(null, txtTag.getText());

		}
	};

	public void clearData() {
		txtName.setValue("");
		txtRank.setValue("0");
		txtURL.setValue("");
		txtDesc.setValue("");
		txtCode.setValue("");
		txtTag.setValue("");
		btnCreateChild.setEnabled(false);
		btnSave.setEnabled(true);
		txtBBSID.setValue("");
		txtCSS.setValue("");
		lbPATH.setText("");
		lbID.setText("新建" + OrgType.getOrgNameByType(m_orgtype) + "信息:");
		btnClearCache.setEnabled(false);
		m_proxy.showPicture(strImagepath, null);
		listType.setSelectedIndex(0);
		sureCanDelete();
	}

	public void enabledEditor(boolean b) {
		btnCreateChild.setEnabled(b);
		btnSave.setEnabled(b);
		sureCanDelete();
	}

	@UiHandler("btnCreateChild")
	void onCreateChild(ClickEvent e) {
		edit(m_whoid, m_orgtype, m_column, null);
	}

	@UiHandler("btnSave")
	void onSave(ClickEvent e) {
		try {
			if (m_column == null) {

				COLUMNObj o = new COLUMNObj();

				if (m_parent == null) {
					o.setNAME(txtName.getValue());
					o.setURL(txtURL.getValue());
					o.setDESCRIPTION(txtDesc.getValue());
					o.setRANKVAL(Integer.valueOf(txtRank.getValue()));
					o.setPID(-1);
					o.setOTYPE(m_orgtype);
					o.setROOTID(-1);
					o.setWHOID(m_whoid);
					o.setTAG(txtTag.getValue());
					o.setCODE(txtCode.getValue());
					o.setDISPLAY(checkDisply.getValue() == true ? 1 : 0);
					o.setUSERVALUE(txtBBSID.getValue());
					o.setCSS(txtCSS.getValue());
					o.setCOLUMNTYPE(listType.getSelectedIndex());
					ServerProxy.SYS_MANAGER.modifyColumn(o, m_modify_handler);
				} else {
					o.setTAG(txtTag.getValue());
					o.setNAME(txtName.getValue());
					o.setURL(txtURL.getValue());
					o.setDESCRIPTION(txtDesc.getValue());
					o.setRANKVAL(Integer.valueOf(txtRank.getValue()));
					o.setPID(m_parent.getID());
					o.setOTYPE(m_orgtype);
					o.setCODE(txtCode.getValue());
					o.setDISPLAY(checkDisply.getValue() == true ? 1 : 0);
					o.setUSERVALUE(txtBBSID.getValue());
					o.setCSS(txtCSS.getValue());
					if (m_parent.getROOTID() == -1) {
						o.setROOTID(m_parent.getID());
					} else {
						o.setROOTID(m_parent.getROOTID());
					}
					o.setCOLUMNTYPE(listType.getSelectedIndex());
					o.setWHOID(m_whoid);
					ServerProxy.SYS_MANAGER.modifyColumn(o, m_modify_handler);
				}

			} else {
				m_column.setTAG(txtTag.getValue());
				m_column.setNAME(txtName.getValue());
				m_column.setURL(txtURL.getValue());
				m_column.setDESCRIPTION(txtDesc.getValue());
				m_column.setRANKVAL(Integer.valueOf(txtRank.getValue()));
				m_column.setCODE(txtCode.getValue());
				m_column.setDISPLAY(checkDisply.getValue() == true ? 1 : 0);
				m_column.setUSERVALUE(txtBBSID.getValue());
				m_column.setCSS(txtCSS.getValue());
				m_column.setCOLUMNTYPE(listType.getSelectedIndex());
				ServerProxy.SYS_MANAGER
						.modifyColumn(m_column, m_modify_handler);
			}
		} catch (NumberFormatException e2) {
			message(e2.getMessage());
		} catch (Exception e1) {
			message(e1.getMessage());
		}
	}

	AsyncCallback<COLUMNObj> m_modify_handler = new AsyncCallback<COLUMNObj>() {

		public void onSuccess(COLUMNObj result) {
			m_column = result;
			fireUpdate();
		}

		public void onFailure(Throwable caught) {

			Window.alert(caught.getMessage());
		}
	};
	private boolean m_candelete = false;

	public void EnabledDelete(Boolean b) {
		m_candelete = b;
		sureCanDelete();
	}

	/**
	 * 确定删除按钮可用
	 */
	void sureCanDelete() {
		if (m_candelete && m_column != null) {
			btnDelete.setEnabled(true);
		} else {
			btnDelete.setEnabled(false);
		}
	}

	// ////////////////////////////////////////////////////////消息显示
	@UiField
	Label lbMessage;

	public void message(String msg) {
		lbMessage.setText(msg);
	}

	// ////////////////////////////////////////////////////////删除节点
	@UiField
	Button btnDelete;
	private AsyncCallback<Boolean> on_delete_handler = new AsyncCallback<Boolean>() {

		public void onSuccess(Boolean result) {
			edit(m_whoid, m_orgtype, null, null);
			sureCanDelete();
			message("删除成功");
			fireUpdate();
		}

		public void onFailure(Throwable caught) {
			message(caught.getMessage());
		}
	};

	@UiHandler("btnDelete")
	void onDelete(ClickEvent e) {
		if (m_column != null && m_column.getID() != null) {
			ServerProxy.SYS_MANAGER.deleteColumn(m_column.getID(),
					on_delete_handler);
		}

	}

	private void fireUpdate() {
		MessageEvent e = new MessageEvent(MessageEvent.UPDATE, 0);
		fireEvent(e);
	}

	private native void init_script()
	/*-{
		var __this = this;

		$wnd.uploadresult = function(data) {
			__this.@com.ksyzt.ksite2.client.column.ColumnEditor::onSaveImage(Ljava/lang/String;)(data);
		};
	}-*/;

	private void onSaveImage(String json) {
		String[] r = GwtUtil.parsePostImageResult(json);
		String rcode = r[0];
		String message = r[1];
		if (rcode.equals("1")) {
			message(SysConst.MSG_UPLOAD_IMAGE_SUCCESS);
			if (m_column != null) {
				m_column.setICON(message);
				ServerProxy.SYS_MANAGER
						.modifyColumn(m_column, m_modify_handler);
			}
			fireUpdate();
		} else {
			message(message);
		}
	}

	@UiField
	ListBox listType;

	@UiField
	HTMLPanel placeholder;

	PostImageProxy m_proxy;
	boolean m_needmove = false;

	public void movefalsh() {
		if (m_needmove == true) {
			showflash();
		}
	}

	@Override
	public void onLoad() {
		super.onLoad();
		init_script();
		m_needmove = true;
		m_proxy = PostImageProxy.getPostImageProxy(SysConst.FLASHID);
	}

	public void showflash() {
		int left = placeholder.getAbsoluteLeft();
		int top = placeholder.getAbsoluteTop();
		m_proxy.moveTo(left, top);
	}

	@Override
	public void onUnload() {
		super.onUnload();
		m_proxy.hide();
	}

	final public static String tag = "Columneditor";
	final public static String strImagepath = "images/column";

	@Override
	public void onResize() {
		showflash();
	}

}
